import React, { useEffect, useState } from 'react'
import { debounce } from 'lodash'
import * as echarts from 'echarts'

import { useRecoilValue } from 'recoil'
import { getMapData } from '@/pages/Home/service'
import { isNullArray, isNullData } from '@/utils'

import { userInfo } from '@/store/userInfo'

export type EChartsOption = echarts.EChartsOption

const useEcharts = (
  // dom实例
  ref: React.RefObject<HTMLDivElement | HTMLCanvasElement | undefined>,
  // echarts配置
  initOption: EChartsOption,
  // 回调函数
  cb?: (ec: echarts.ECharts) => any,
  // 主题
  theme = '',
): {
  echart: echarts.ECharts | undefined
  cb: (ec: echarts.ECharts) => void
} => {
  const userinfo = useRecoilValue(userInfo)
  const [chart, setChart] = useState<echarts.ECharts>()

  // 判断传入得是不是回调函数
  const callback = (ec: echarts.ECharts) => {
    if (typeof cb === 'function') {
      cb(ec)
    }
  }

  // 加载地图数据
  const getMap = async () => {
    const res = await getMapData({
      platformId: userinfo.platformId,
    })
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      echarts.registerMap('Zhejiang', JSON.parse(res.data.geoJson))
    }
  }

  const init = async () => {
    // 初始化
    const c = echarts.init(ref.current!, theme)
    await getMap()
    // 存储实例
    setChart(c)
    c.setOption(initOption)
    // 调用回调函数并将实例传入进去
    callback(c)
  }

  useEffect(() => {
    if (ref.current) {
      init()
    }
  }, [ref])

  useEffect(() => {
    // 在这里监听，放在里面会内存泄漏，一个优化吧
    const resizeHandler = debounce(() => {
      chart?.resize()
    }, 100)

    window.addEventListener('resize', resizeHandler)

    return () => {
      chart?.dispose()

      window.removeEventListener('resize', resizeHandler)
    }
  }, [chart])

  return {
    echart: chart,
    cb: callback,
  }
}

export default useEcharts
